package com.youlu.campus.service.share.impl;

import com.mongodb.client.result.UpdateResult;
import com.youlu.campus.entity.share.QQMiniProgramShareRecord;
import com.youlu.campus.service.share.QQMiniProgramShareRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.Objects;

@Slf4j
@Service
public class QQMiniProgramShareRecordServiceImpl implements QQMiniProgramShareRecordService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public QQMiniProgramShareRecord findByShareToUserId(@NotNull String userId, @NotNull String appId) {
        Query query = new Query().addCriteria(Criteria.where("shareToUserId").is(userId).and("appId").is(appId));
        return mongoTemplate.findOne(query, QQMiniProgramShareRecord.class);
    }

    @Override
    public boolean create(@NotNull QQMiniProgramShareRecord req) {
        req.setId(null);
        req.setCreatedTime(new Date());
        req = mongoTemplate.insert(req);
        if (StringUtils.isNotBlank(req.getId())) {
            return true;
        }
        return false;
    }

    @Override
    public boolean update(@NotNull QQMiniProgramShareRecord req) {
        Query query = new Query().addCriteria(Criteria.where("id").is(req.getId()));
        Update update = new Update();
        if (Objects.nonNull(req.getStatus())) {
            update.set("status", req.getStatus());
            update.set("updatedTime", new Date());
        }
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, QQMiniProgramShareRecord.class);
        return updateResult.getModifiedCount() > 0 ? true : false;
    }

    @Override
    public boolean createInviteRecord(String appId, String shareByUId, String shareToUId) {
        log.info(":>>> 开始创建平台级别的邀请记录:{},{},{}", appId, shareByUId, shareToUId);
        QQMiniProgramShareRecord record = this.findByShareToUserId(shareToUId, appId);
        if (Objects.nonNull(record)) {
            log.error(":>>> 小程序:{} 用户:{} 已经被分享过",appId,shareByUId);
            return false;
        }
        record = new QQMiniProgramShareRecord();
        record.setAppId(appId);
        record.setPlatform("qq");
        record.setShareByUserId(shareByUId);
        record.setShareToUserId(shareToUId);
        record.setStatus(1);
        create(record);
        return create(record);
    }
}
